package com.haihui.platform.service.impl.roles;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.haihui.platform.entity.TreeBeans;
import com.haihui.platform.utils.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import com.haihui.platform.dao.roles.ResourceDao;
import com.haihui.platform.entity.Resource;
import com.haihui.platform.service.roles.ResourceService;
import com.haihui.platform.utils.StringUtils;


@Service
public class ResourceServiceImpl implements ResourceService{

	@Autowired
	private ResourceDao resourceDao;

	@Override
	public List<TreeBeans> getParentTree(Long filterId){
		List<Resource> resources = resourceDao.getAll();
		fliterWithId(resources, filterId);
		return toTreeBeans(resources);
	}
	private void fliterWithId(List<Resource> resources, Long filterId) {
		if (filterId != null && CollectionUtils.isNotEmpty(resources)) {
			Iterator<Resource> it = resources.iterator();
			Resource resource = null;
			while (it.hasNext()) {
				resource = it.next();
				if (filterId.equals(resource.getResId()) || StringUtils.contains(resource.getParentIds(), String.valueOf(filterId))) {
					it.remove();
				}
			}
		}
	}
	private List<TreeBeans> toTreeBeans(List<Resource> resources) {
		List<TreeBeans> trees = null;
		if (CollectionUtils.isNotEmpty(resources)) {
			trees = new ArrayList<TreeBeans>(resources.size());
			TreeBeans treebean = null;
			for (Resource category : resources) {
				treebean = new TreeBeans();
				treebean.setId(category.getResId());
				treebean.setName(category.getResName());
				treebean.setpId(category.getParentId());
				trees.add(treebean);
			}

		} else {
			trees = new ArrayList<TreeBeans>(0);
		}
		return trees;
	}
	@Override
	public List<Map<String, Object>> getResourceByUser(long id) {
		return resourceDao.getResourceByUser(id);
	}

	@Override
	public Integer add(Resource res) {
		return resourceDao.add(res);
	}

	@Override
	public Integer update(Resource res) {
		return resourceDao.update(res);
	}

	@Override
	public List<Resource> list(Resource res) {
		return resourceDao.list(res);
	}

	@Override
	public Integer count(Resource res) {
		return resourceDao.count(res);
	}

	@Override
	public Resource detail(Resource res) {
		return resourceDao.detail(res);
	}


	@Override
	public List<Resource> getAll() {
		return resourceDao.getAll();
	}
	@Override
	public List<Map<String, Object>> resByRole(String roleId) {
		return resourceDao.resByRole(roleId);
	}


}
